#!/bin/bash
# THIS DRIVER WRITTEN BY MATTHEW VONA FOR THE LGR N2O CO.
# THE PRINCIPLE OF OPERATION IS THAT THE DRIVER WILL SIT AND PASSIVELY AGGREGATE DATA
# INTO DATA FILES WHICH ARE THEN PROCESSED FOR INCLUSION INTO THE RAW DATARECORD.
# THE RATE OF DATA COLLECTION SHOULD BE INSIGNIFICANT. 
# THIS SCRIPT RERQUIRES A PARALLEL INGESTER BE USED TO STATISTICALLY DIGEST THE DATA AND RECORD IT IN THE 
# CARBLogger DATA RECORD. 
function qc {
		number_of_fields=`wc -w $1`
		echo $number_of_fields
	}

################################################################################################
#
# SET THE PORT AND CLEAR THE FIRST DATA PROCESSING FILE
#
################################################################################################
if !(stty -F $1 raw ispeed $2 ospeed $2 cs8 -ignpar -cstopb -echo); then
	{
		echo "Failed to initialize the serial port. Exiting"
		exit 1;

	}
fi
#GET the present location
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Begin the main loop
while [ 1 ]; 
do
	


		stamp=`date '+%H %M %S %N' | tr -d '\n'`
		hrbin=`echo $stamp | awk '{ print $1 }'`	
		minbin=`echo $stamp | awk '{ print $2 }'`
	#MAKE A FOLDER FOR THE HOUR IF IT DOSEN'T EXIST	
	if [ ! -d "${DIR}/${hrbin}" ]; then
			mkdir ${DIR}/${hrbin}
			awk -v this_stamp="$stamp" '{ print this_stamp" " $1 " " $2 " " $3 " " $5+0 " " $7+0 " " $9+0 " " $11+0 " " $13+0 " " $15+0" " $17+0 ; fflush(); exit}' ${1} | sed 's/\.[0-9][0-9][0-9],//g' |sed 's/,//g'  >> ${DIR}/${hrbin}/${minbin}.dat
		else
			awk -v this_stamp="$stamp" '{ print this_stamp" " $1 " " $2 " " $3 " " $5+0 " " $7+0 " " $9+0 " " $11+0 " " $13+0 " " $15+0" " $17+0 ; fflush(); exit }' ${1} | sed 's/\.[0-9][0-9][0-9],//g' | sed 's/,//g' >> ${DIR}/${hrbin}/${minbin}.dat			
	fi
	

done
